package com.jyw.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jyw.R;
import com.jyw.network.OkHttpManager;
import com.jyw.network.Server;
import com.jyw.pojo.Address;
import com.jyw.pojo.EventBusTypes;
import com.jyw.utils.DimenUtils;
import com.victor.loading.rotate.RotateLoading;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author simonw
 * @version 1.0
 * @created 2017/1/2
 */

public class AddressesActivity extends BaseActivity {
    private RecyclerView recycler;
    private AddressesAdapter mAdapter;
    private RotateLoading rotateLoading;

    private String defaultId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_addresses);

        findViewById(R.id.btn_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(AddressesActivity.this, AddressAddActivity.class));
            }
        });

        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        rotateLoading = (RotateLoading) findViewById(R.id.rotateloading);
        recycler = (RecyclerView) findViewById(R.id.recycler);
        recycler.setLayoutManager(new LinearLayoutManager(AddressesActivity.this));
        recycler.addItemDecoration(new SpacesItemDecoration(DimenUtils.dip2px(AddressesActivity.this, 0f),
                DimenUtils.dip2px(AddressesActivity.this, 8f)));
        recycler.setAdapter(mAdapter = new AddressesAdapter(null));

        loadData();

    }

    class AddressesAdapter extends RecyclerView.Adapter<AddressesAdapter.AddresesHolder> {
        private List<Address> data;

        AddressesAdapter(List<Address> data) {
            this.data = data;
        }

        void swapData(List<Address> data) {
            this.data = data;
            notifyDataSetChanged();
        }

        @SuppressLint("InflateParams")
        @Override
        public AddresesHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new AddressesAdapter.AddresesHolder(LayoutInflater.from(AddressesActivity.this).inflate(R.layout.item_address, null));
        }

        @Override
        public void onBindViewHolder(AddressesAdapter.AddresesHolder holder, final int position) {
            Address a = data.get(position);
            if (a.getIs_default().equals("1")) {
                holder.view.setBackgroundResource(R.drawable.bg_rectangle_green);
                holder.ivSelected.setVisibility(View.VISIBLE);
                holder.tvName.setTextColor(Color.WHITE);
                holder.tvPhone.setTextColor(Color.WHITE);
                holder.tvAddress.setTextColor(Color.WHITE);
            }else{
                holder.view.setBackgroundResource(R.drawable.bg_rectangle_white);
                holder.ivSelected.setVisibility(View.INVISIBLE);
                holder.tvName.setTextColor(getResources().getColor(R.color.text_black_light));
                holder.tvPhone.setTextColor(getResources().getColor(R.color.text_black_light));
                holder.tvAddress.setTextColor(getResources().getColor(R.color.text_black_light));
            }
            holder.tvName.setText(a.getName());
            holder.tvPhone.setText(a.getPhone());
            holder.tvAddress.setText(a.getCity() + " " + a.getCircle() + " " + a.getDetail());

            if (getIntent().getBooleanExtra("isForDefault", false)) {
                holder.view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (Address a : data) {
                            a.setIs_default("0");
                        }
                        data.get(position).setIs_default("1");
                        defaultId = data.get(position).getId();
                        notifyDataSetChanged();
                    }
                });
            } else {
                holder.view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        EventBus.getDefault().post(new EventBusTypes.AddressSelected(data.get(position)));
                        AddressesActivity.this.finish();
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return data == null ? 0 : data.size();
        }

        class AddresesHolder extends RecyclerView.ViewHolder {
            View view;
            ImageView ivSelected;
            TextView tvName, tvPhone, tvAddress;

            AddresesHolder(View itemView) {
                super(itemView);
                this.view = itemView;
                ivSelected = (ImageView) itemView.findViewById(R.id.iv_selected);
                tvName = (TextView) itemView.findViewById(R.id.tv_name);
                tvPhone = (TextView) itemView.findViewById(R.id.tv_phone);
                tvAddress = (TextView) itemView.findViewById(R.id.tv_address);
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (getIntent().getBooleanExtra("isForDefault", false)) {
            Request request = new Request.Builder().
                    url(Server.MOG_ADDRESS_DEFAULT + "?id_data=" + defaultId).
                    build();
            OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    OkHttpManager.backgroundThreadShortToast(AddressesActivity.this, "错误：" + e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                }
            });
        }
    }

    private void loadData() {
        rotateLoading.start();
        Request request = new Request.Builder().
                url(Server.GET_ADDRESS + "?phone_data=" + getPrefs().getString("phone", "")).
                build();
        OkHttpManager.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                OkHttpManager.backgroundThreadShortToast(AddressesActivity.this, "错误：" + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                JSONArray arr;
                final List<Address> addresses = new ArrayList<>();
                try {
                    arr = new JSONArray(response.body().string());
                    if (arr.length() > 0) {
                        Gson gson = new Gson();
                        for (int i = 0; i < arr.length(); i++) {
                            addresses.add(gson.fromJson(arr.get(i).toString(), Address.class));
                        }

                        new AsyncTask<Void, Void, Void>() {
                            @Override
                            protected Void doInBackground(Void... params) {
                                return null;
                            }

                            @Override
                            protected void onPostExecute(Void aVoid) {
                                super.onPostExecute(aVoid);
                                rotateLoading.stop();
                                mAdapter.swapData(addresses);
                            }
                        }.execute();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    class SpacesItemDecoration extends RecyclerView.ItemDecoration {
        private int leftRight;
        private int topBottom;

        SpacesItemDecoration(int leftRight, int topBottom) {
            this.leftRight = leftRight;
            this.topBottom = topBottom;
        }

        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            super.onDraw(c, parent, state);
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
            //竖直方向的
            if (layoutManager.getOrientation() == LinearLayoutManager.VERTICAL) {
                //最后一项需要 bottom
                if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                    outRect.bottom = topBottom;
                }
                outRect.top = topBottom;
                outRect.left = leftRight;
                outRect.right = leftRight;
            } else {
                //最后一项需要right
                if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                    outRect.right = leftRight;
                }
                outRect.top = topBottom;
                outRect.left = leftRight;
                outRect.bottom = topBottom;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(EventBusTypes.AddressAdded type) {
        loadData();
    }
}
